﻿using System;
using System.Threading;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Threading;
using Assergs.Windows;
using Bookvar.ApplicationModel;
using Bookvar.ServiceModel;
using Bookvar.Common.ErrorSubmitterService;
using BookvarWpf.Windows;

namespace BookvarWpf
{
    /// <summary>
    /// Interaction logic for LiveImagesWindow.xaml
    /// </summary>
    public partial class SubmitBugWindow : BookvarToolWindow
    {
        public string BugDescription
        {
            get
            {
                TextRange textRange = new TextRange(txtBugDescription.Document.ContentStart, txtBugDescription.Document.ContentEnd);
                return textRange.Text;
            }
            set {
                txtBugDescription.Document.Blocks.Clear();
                txtBugDescription.Document.Blocks.Add(new Paragraph(new Run(value)));
            }
        }

        public string BugTitle
        {
            get { return txtBugSubject.Text; }
            set { txtBugSubject.Text = value; }
        }

        private delegate void SubmitDelegate(string statusMessage);

        private Thread workerThread;

        public SubmitBugWindow()
        {
            InitializeComponent();
            txtName.Text = System.Threading.Thread.CurrentPrincipal.Identity.Name;
        }

        private void OnSubmitClicked( object sender, RoutedEventArgs e )
        {
            //TODO: validate data
            progressAnimation.Start();
            ErrorReport errorReport = new ErrorReport();
            errorReport.Title = txtBugSubject.Text.Trim();
            errorReport.ReporterMail = txtEmail.Text.Trim();
            errorReport.ErrorMessage = BugDescription;
            errorReport.ErrorTypeID = 1;
            errorReport.ReportBy = txtName.Text.Trim();
            errorReport.ReportOn = DateTime.Now;
            
            workerThread = new Thread( ExecuteSubmit );
            workerThread.Start(errorReport);
        }

        private void ShowSubmitResult(string statusMessage)
        {
            progressAnimation.Stop();
            lblStatus.Content = statusMessage;
            lblStatus.Visibility = Visibility.Visible;
        }

        private void ExecuteSubmit(object obj)
        {
            IErrorReporter errorReporter = BookvarApplication.Current.ServiceLayer.GetService<IErrorReporter>();
            bool status = errorReporter.ReportError(obj);

            string statusString = status ? "Error sent successfully." : "Error can not be sent now. Try again leter.";

            Dispatcher.BeginInvoke(DispatcherPriority.Send, new SubmitDelegate(ShowSubmitResult), statusString);
        }
    }
}